#include <stdint.h>
#include <stdbool.h>

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

static char* fn = "test.lua";

static void error(lua_State *L, const char *fmt, ...)
{
	va_list argp;
	va_start(argp, fmt);
	vfprintf(stdout, fmt, argp);
	va_end(argp);
	lua_close(L);
	exit(EXIT_FAILURE);
}

/* assume that table is on the stack top */
int getfield (lua_State *L, const char *key)
{
	int result;
	lua_pushstring(L, key);
	lua_gettable(L, -2);  /* get background[key] */
	if (!lua_isnumber(L, -1))
		error(L, "invalid component in background color");
	result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);  /* remove number */
	return result;
}

static void load(char *filename)
{
	lua_State *L = luaL_newstate();
	luaL_openlibs(L);

	if (luaL_loadfile(L, filename) || lua_pcall(L, 0, 0, 0))
		error(L, "cannot run configuration file: %s",
		      lua_tostring(L, -1));

	lua_getglobal(L, "width");
	lua_getglobal(L, "height");
	lua_getglobal(L, "user");

	if (!lua_isnumber(L, -3))
		error(L, "`width' should be a number\n");
	if (!lua_isnumber(L, -2))
		error(L, "`height' should be a number\n");
	if (!lua_isstring(L, -1))
		error(L, "`user' should be a string\n");

	printf("user:%s\n",lua_tostring(L, -1));
	printf("width:%d\n",(int)lua_tonumber(L, -2));
	printf("height:%d\n",(int)lua_tonumber(L, -3));

	lua_getglobal(L, "background");
	if (!lua_istable(L, -1))
		error(L, "`background' is not a valid color table");

	printf("background:\n");
	printf("\tred:%d\n",getfield(L,"r"));
	printf("\tgreen:%d\n",getfield(L,"g"));
	printf("\tblue:%d\n",getfield(L,"b"));

	lua_close(L);
}

int main(int argc, char **argv)
{
	load(fn);
	return (0);
}
